package fun.hijklmn.magic.resource.server.service.impl;

import fun.hijklmn.magic.common.enums.ResponseCodeEnum;
import fun.hijklmn.magic.common.utils.UUIDUtil;
import fun.hijklmn.magic.resource.common.enums.FileCatalogEnum;
import fun.hijklmn.magic.resource.common.enums.FileTypeEnum;
import fun.hijklmn.magic.resource.common.transport.UploadFileRequest;
import fun.hijklmn.magic.resource.common.transport.UploadFileResponse;
import fun.hijklmn.magic.resource.common.utils.FileUtil;
import fun.hijklmn.magic.resource.server.config.ResourceProperties;
import fun.hijklmn.magic.resource.server.pojo.Resource;
import fun.hijklmn.magic.resource.server.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description
 * @Author fs
 * @Date 2021/5/25 16:43
 * @Version 0.0.1-SNAPSHOT
 **/
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ResourceProperties resourceProperties;

    @Override
    public UploadFileResponse upload(UploadFileRequest uploadFileRequest) {

        UploadFileResponse uploadFileResponse = new UploadFileResponse();

        if (uploadFileRequest == null) {
            uploadFileResponse.setCode(ResponseCodeEnum.INVALID_PARAM.code());
            uploadFileResponse.setMessage("参数为空");
        }

        if (StringUtils.isEmpty(uploadFileRequest.getFileName())) {
            uploadFileResponse.setCode(ResponseCodeEnum.INVALID_PARAM.code());
            uploadFileResponse.setMessage("文件名称为空");
        }

        if (StringUtils.isEmpty(uploadFileRequest.getKey())) {
            uploadFileResponse.setCode(ResponseCodeEnum.INVALID_PARAM.code());
            uploadFileResponse.setMessage("Key为空");
        }

        if (uploadFileRequest.getInputStream() == null) {
            uploadFileResponse.setCode(ResponseCodeEnum.INVALID_PARAM.code());
            uploadFileResponse.setMessage("文件内容为空");
        }

        File fileDir = new File(resourceProperties.getLocalDir().concat(File.separator).concat(uploadFileRequest.getKey()));

        if (!fileDir.exists() || !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }

        try {

            List<Resource> resourceList = mongoTemplate.find(new Query(Criteria.where("key").is(uploadFileRequest.getKey()).and("name").is(uploadFileRequest.getFileName()).and("type").is(FileTypeEnum.IMAGE.type())), Resource.class, FileTypeEnum.IMAGE.type());

            FileUtil.transTo(uploadFileRequest.getInputStream(), fileDir.getAbsolutePath().concat(File.separator).concat(uploadFileRequest.getFileName()));
            uploadFileResponse.setSize((long) uploadFileRequest.getInputStream().available());
            uploadFileResponse.setCode(ResponseCodeEnum.SUCCESS.code());
            uploadFileResponse.setMessage("成功");
            uploadFileResponse.setFileName(uploadFileRequest.getFileName());
            uploadFileResponse.setKey(uploadFileRequest.getKey());
            uploadFileResponse.setFileCatalog(FileCatalogEnum.JPEG.type());

            URL url = new URL(resourceProperties.getRootUrl().concat("/").concat(uploadFileRequest.getKey()).concat("/").concat(uploadFileRequest.getFileName()));

            uploadFileResponse.setUrl(url.toString());

            if (CollectionUtils.isEmpty(resourceList)) {
                Resource resource = new Resource();
                resource.setCreatedTime(LocalDateTime.now());
                resource.setId(UUIDUtil.uuid());
                resource.setKey(uploadFileRequest.getKey());
                resource.setName(uploadFileRequest.getFileName());
                resource.setStatus(1);
                resource.setType(FileTypeEnum.IMAGE.type());
                resource.setSize((long) uploadFileRequest.getInputStream().available());
                mongoTemplate.insert(resource, FileTypeEnum.IMAGE.type());
            } else {
                Resource resource = resourceList.get(0);
                Update update = new Update();
                update.set("size", uploadFileRequest.getInputStream().available());
                mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(resource.getId())), update, FileTypeEnum.IMAGE.type());
            }

        } catch (IOException e) {
            log.error("----------->上传文件失败", e);
            uploadFileResponse.setCode(ResponseCodeEnum.ERROR.code());
            uploadFileResponse.setMessage("上传失败");
            return uploadFileResponse;
        }

        return uploadFileResponse;

    }

}
